package com.ceadeal.admin.group.wechat.util;

import com.ceadeal.admin.group.wechat.web.WxEntryController;
import com.ceadeal.admin.util.StringUtil;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Http请求工具类
 *
 * @author Westin Yang
 * @date 2017-03-31 21:29:13
 */
public class HttpClientUtil {
    private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     * 描述：Get请求
     *
     * @param
     * @return
     * @throws
     *
     * @author Westin Yang
     * @date 2017-03-31 21:33:21
     */
    public static String httpGet(String url) {
        log.info("HTTP GET => url:{}", url);
        if (StringUtil.isEmpty(url)) {
            return "";
        }

        String responseBody = "";
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            log.info("HTTP GET => execute");
            response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                log.info("HTTP GET => statusCode:{}", statusCode);
                HttpEntity httpEntity = response.getEntity();
                responseBody = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);
            } else {
                log.warn("HTTP GET => statusCode:{}", statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                }
            }
        }
        log.warn("HTTP GET => responseBody:{}", responseBody);
        return responseBody;
    }

}
